import grails.util.Environment
import org.springframework.core.io.ClassPathResource
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import com.eso.frame.core.InitialLoaderManager

class BootStrap {

    InitialLoaderManager initialLoaderManager;

    def init = { servletContext ->

        loadConfigProperties(servletContext);

        initialLoaderManager.start();
    }


    def loadConfigProperties = {servletContext ->
        String envName = Environment.getCurrent().getName();
        String configFile = "config.properties";
        ClassPathResource resource = new ClassPathResource("/${envName}." + configFile);

        if (!resource.exists()) resource = new ClassPathResource("/" + configFile);
        if (!resource.exists()) return;

        ConfigObject config = ConfigurationHolder.config;
        Properties prop = new Properties();
        prop.load(new InputStreamReader(resource.getInputStream(), "UTF-8"));
        Map map = new HashMap(prop)
        prop.each {key, value ->
            if (!value) return;
            map.each {
                if (!it.value) return
                it.value = it.value.replace("@$key", value);
            }
        }

        config.putAll(map);

        println "config=$config"
    }


    def destroy = {
    }
}
